import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/update_task_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';

import 'bean/department_response_bean.dart';
import 'bean/user_select_sort_save_response_bean.dart';

///单选部门页面
///添加用户、考勤更多记录用到
class DepartmentWidget extends StatefulWidget {
  final String selectedId;
  final String departmentType;
  final String fuid;
  final bool selectOnly;

  const DepartmentWidget(
      {Key key,
      this.selectedId,
      this.departmentType = "00",
      this.fuid,
      this.selectOnly})
      : super(key: key);

  @override
  _DepartmentWidgetState createState() => _DepartmentWidgetState();

  ///跳转方法
  ///[selectOnly] 仅选择，不走接口保存
  ///
  static Future<EditTextAndValue> navigatorPush(
      BuildContext context, String selectedId,
      {String fuid, bool selectOnly}) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      DepartmentWidget(
        selectedId: selectedId,
        fuid: fuid,
      ),
    )..then((value) {
        print("返回值：${value}");
      });
  }
}

class _DepartmentWidgetState extends BaseState<DepartmentWidget> {
  bool isLightUp = false;
  String mDepartmentText;

  CommonListPageWidgetState<DepartmentListItemBean, DepartmentResponseBean>
      _mState;
  String roleId = UserRepository.getInstance().userData.comUser.roleid;

  void setCommonListState(
      CommonListPageWidgetState<DepartmentListItemBean, DepartmentResponseBean>
          state) {
    _mState = state;
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
      Scaffold(
        // resizeToAvoidBottomInset: false,
        // resizeToAvoidBottomPadding: false,
        backgroundColor: Color(0xFF191E31),
        body: CommonPackUpKeyboardWidget(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              _toTopBarWidget(),
              if (roleId == "99") _searchDepartmentWidget(),
              //下划线
              if (roleId == "99")
                Container(
                  height: 1,
                  padding: const EdgeInsets.only(
                    left: 21,
                  ),
                  child: Divider(
                    height: 1.0,
                    indent: 0.0,
                    color: Color(0xFF303546),
                  ),
                ),
              SizedBox(
                height: 10,
              ),
              Expanded(
                child: DepartmentSingleSelectWidget(
                  selectedId: widget.selectedId,
                ),
              ),
            ],
          ),
        ),
      ),
      navigationBarColor: Color(0xFF191E31),
    );
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 50,
      color: Color(0xFF3A3F50),
      child: CommonEditCallbackWidget(
        hintText: "请输入部门名称",
        onChanged: (String departmentText) {
          mDepartmentText = departmentText;
          if (departmentText == null ||
              departmentText == "" ||
              departmentText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
        onSubmitted: (String departmentText) {
          mDepartmentText = departmentText;
          if (departmentText == null ||
              departmentText == "" ||
              departmentText.trim().isEmpty)
            isLightUp = false;
          else
            isLightUp = true;
          setState(() {});
        },
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "部门",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    if (roleId == "99")
      return Container(
        child: CommonFixedHeightConfirmButtonWidget(
          isAlive: isLightUp,
          width: 48,
          height: 24,
          unSelectBgColor:
              ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
          selectedBgColor:
              ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              fontWeight: FontWeight.w600),
          selectedTextStyle: TextStyle(
              color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          text: "确定",
          onTap: () {
            //提交按钮
            if (isLightUp) {
              _httpSave();
            }
          },
        ),
      );
  }

  void _httpSave() {
    if (mDepartmentText == null || mDepartmentText.isEmpty) {
      VgToastUtils.toast(context, "请输入部门名称");
      return;
    }
    List<DepartmentListItemBean> departmentList = _mState?.data;
    if (departmentList == null || departmentList.isEmpty) {
      _saveDepartmentNameHttp();
      return;
    }
    for (DepartmentListItemBean item in departmentList) {
      if (item?.name == mDepartmentText) {
        _pop(item);
        return;
      }
    }
    _saveDepartmentNameHttp();
  }

  ///返回部门选中值
  void _pop(DepartmentListItemBean itemBean) {
    if (itemBean == null) {
      return;
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(value: itemBean.id, editText: itemBean.name));
  }

  ///保存接口
  void _saveDepartmentNameHttp() {
    if (mDepartmentText == null || mDepartmentText.isEmpty) {
      VgToastUtils.toast(context, "部门名称不能为空");
      return;
    }
    VgHudUtils.show(context, "保存中");
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appAddChooseInfo",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "name": mDepartmentText?.trim() ?? "",
          "type": widget.departmentType,
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          VgHudUtils.hide(context);
          if (val == null) {
            return;
          }
          UserSelectSortSaveResponseBean successBean =
              UserSelectSortSaveResponseBean.fromMap(val);
          if (successBean == null ||
              successBean.data == null ||
              successBean.data.isEmpty) {
            VgToastUtils.toast(context, "部门添加返回值错误");
            return;
          }
          DepartmentListItemBean departmentListItemBean =
              new DepartmentListItemBean();

          successBean.data.forEach((element) {
            if (element?.name != null &&
                element?.name != "" &&
                element?.name == mDepartmentText) {
              departmentListItemBean.id = element.id;
            }
          });
          departmentListItemBean.name = mDepartmentText;
          _pop(departmentListItemBean);
          // _pop(DepartmentListItemBean()..id = successBean.data..name = mDepartmentText);
        }, onError: (String msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }
}

///部门选择列表
class DepartmentSingleSelectWidget extends StatefulWidget {
  final String selectedId;
  final String fuid;
  final bool selectOnly;

  const DepartmentSingleSelectWidget(
      {Key key, this.selectedId, this.fuid, this.selectOnly})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return DepartmentSingleSelectState();
  }
}

class DepartmentSingleSelectState
    extends BaseState<DepartmentSingleSelectWidget> {
  String selectedId;
  UpdateTaskViewModel viewModel;

  String cacheKey;

  ///上次选择的部门
  List<String> cacheIds=List();

  @override
  Widget build(BuildContext context) {
    return _toCustomListWidget();
  }

  @override
  void initState() {
    super.initState();
    viewModel = UpdateTaskViewModel(this);
    selectedId = widget.selectedId;
    cacheKey = KEY_SELECT_DEPARTMENT +
        UserRepository.getInstance().getCacheKeySuffix();
    SharePreferenceUtil.getStringList(cacheKey).then((value) {
      if (value != null) {
        cacheIds = value;
        setState(() {});
      }
    });
  }

  //封装的列表
  Widget _toCustomListWidget() {
    return CommonListPageWidget<DepartmentListItemBean, DepartmentResponseBean>(
      enablePullUp: false,
      enablePullDown: false,
      queryMapFunc: (int page) => {
        "authId": UserRepository.getInstance().authId ?? "",
        "name": "",
        "type": "00",
      },
      parseDataFunc: (VgHttpResponse resp) {
        DepartmentResponseBean bean =
            DepartmentResponseBean.fromMap(resp?.data);
        if (cacheIds.isNotEmpty &&
            bean.data != null &&
            bean.data.length > 0) {
          int selectIndex =
              bean.data.indexWhere((element) => cacheIds.contains(element.id));
          if (selectIndex >= 0) {
            DepartmentListItemBean temp = bean.data[0];
            bean.data[0] = bean.data[selectIndex];
            bean.data[selectIndex] = temp;
          } else {
            selectedId = null;
          }
        }
        return bean;
      },
      itemBuilder:
          (BuildContext context, int index, DepartmentListItemBean itemBean) {
        return _toListItemWidget(context, index, itemBean);
      },
      //分割器构造器
      separatorBuilder: (context, int index, _) {
        return Container(
          height: 0.5,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          padding: const EdgeInsets.only(left: 15),
          child: Container(
            color: Color(0xFF303546),
          ),
        );
        // return divider;
      },
      netUrl:ServerApi.BASE_URL + "app/appChooseInfo",
      cacheKey:ServerApi.BASE_URL +
          "app/appChooseInfo" +
          UserRepository.getInstance().getCacheKeySuffix() +
          'department',
      needCache: true,
      httpType: VgHttpType.post,
    );
  }

  Widget _toListItemWidget(
      BuildContext context, int index, DepartmentListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        //判断字体是否选中
        // departmentText =
        selectedId = itemBean.id;
        setState(() {});
        //收键盘方法
        // FocusScope.of(context).requestFocus(FocusNode());
        VgToolUtils.removeAllFocus(context);
        Future.delayed(Duration(milliseconds: 10), () {
          _pop(itemBean);
        });
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 50,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Text(
                itemBean?.name ?? "",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                  color: itemBean.id != selectedId
                      ? Color(0xFFD0E0F7)
                      : Color(0xFF1890FF),
                  fontSize: 14,
                ),
              ),
            ),
            Spacer(),
            GestureDetector(
              onTap: () async {
                VgToolUtils.removeAllFocus(context);
                if (widget.fuid == null || widget.selectOnly) {
                  RouterUtils.pop(context,
                      result: EditTextAndValue(editText: '', value: null));
                } else {
                  loading(true, msg: "正在设置");
                  viewModel?.AppUpdateChooseInfo(context, widget?.fuid, "00");
                }
              },
              child: Visibility(
                visible: itemBean.id == selectedId,
                child: Padding(
                  padding: const EdgeInsets.all(5.0),
                  child: Text(
                    "取消选择",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Color(0xFF5E687C),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///返回部门选中值
  void _pop(DepartmentListItemBean itemBean) {
    if (itemBean == null) {
      return;
    }
    if(StringUtils.isNotEmpty(itemBean.id)){
      cacheIds.clear();
      cacheIds.add(itemBean.id);
      SharePreferenceUtil.putStringList(cacheKey,cacheIds);
    }
    RouterUtils.pop(context,
        result: EditTextAndValue(value: itemBean.id, editText: itemBean.name));
  }
}
